package com.shipwe.loans.ui.activity

import android.annotation.SuppressLint
import android.view.View
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.shipwe.adapter.ShipweOnItemChildClickListener
import com.shipwe.loans.R
import com.shipwe.loans.configs.ShipweConfigs
import com.shipwe.loans.databinding.ActivityMainBinding
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.ui.adapter.MainTabAdapter
import com.shipwe.loans.ui.factory.MainFragmentFactory
import com.shipwe.loans.ui.fragment.FragmentMenu
import com.shipwe.loans.ui.presenter.MainPresenter
import com.shipwe.loans.ui.view.IMainView
import com.shipwe.loans.utils.dialog.LuckyDrawGiftDialog
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.event.AppEventPointHelper
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomDataHelper
import com.shipwe.loans.utils.log.ShipweLogger
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:39
 * @Annotation：主页
 */
class ActivityMain: ShipweActivity(), IMainView {
    lateinit var binding: ActivityMainBinding
    var presenter: MainPresenter? = null
    private var tabAdapter: MainTabAdapter? = null
    private var fragmentManager: FragmentManager? = null
    override fun getShipweRootView(): View {
        binding = ActivityMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        setBackExit(true)
        showMainFragmentPage()
        initMainTabGridView()
        addMainMenuFragment()
    }

    override fun initShipweListener() {
        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (presenter?.curtIndex == position){
                    return
                }
                presenter?.curtIndex = position
                presenter?.setMainCurrentItemIndex(position)
            }
        })
    }

    override fun initShipweData() {
        presenter = MainPresenter(this)
        showShipweLoading()
        presenter?.loadMainTabList()
        presenter?.loadAppProcessAction()
        binding.viewPager.currentItem = 0

        //加载保存自定义数据
        CustomDataHelper.loadShipweCustomDataAction()
    }

    /**
     * 添加页面
     */
    private fun showMainFragmentPage(){
        val pageAdapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = 3
            override fun createFragment(position: Int): Fragment =
                MainFragmentFactory.create(position)
        }
        binding.viewPager.adapter = pageAdapter
    }

    /**
     * 初始化Tab列表
     */
    private fun initMainTabGridView() {
        binding.mainTab.layoutManager = GridLayoutManager(getContext(), 3)
        tabAdapter = MainTabAdapter(binding.mainTab)
        binding.mainTab.adapter = tabAdapter
        binding.mainTab.itemAnimator = DefaultItemAnimator()
        tabAdapter?.setOnItemChildClickListener(ShipweOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.mainTabItem) {//切换item
                binding.viewPager.currentItem = position
            }
        })
    }

    /**
     * 添加侧边菜单
     */
    private fun addMainMenuFragment(){
        if (fragmentManager == null) {
            fragmentManager = supportFragmentManager
        }
        fragmentManager!!
            .beginTransaction()
            .add(R.id.mainMenu, FragmentMenu(binding.mainDrawer)) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    override fun showMainTabList(tabList: ArrayList<JSONObject>) {
        tabAdapter?.data = tabList
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun notifyMainTabDataChanged(curtIndex: Int) {
        tabAdapter?.notifyDataSetChanged()
        if (curtIndex == 0 || curtIndex == 1){
            presenter?.loadAppProductListAction()
        }
    }

    /**
     * 展示个人中心
     */
    fun showMainMenuFragment(eventRemark: String){
        val isOpen = binding.mainDrawer.isDrawerOpen(GravityCompat.START)
        if (isOpen){//是否打开
            binding.mainDrawer.closeDrawer(GravityCompat.START,true)
        } else {
            binding.mainDrawer.openDrawer(GravityCompat.START,true)
        }
        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER,eventRemark)
    }

    /**
     * 签到成功
     */
    override fun showMainSignSuccessDialog(signPoints: String) {
        val giftDialog = LuckyDrawGiftDialog(this,"Sign Success Points:$signPoints",object : LuckyDrawGiftDialog.IDialogCallback{
            override fun onClick(view: View?) {

            }
        })
        giftDialog.setCancelable(true)
        giftDialog.setCanceledOnTouchOutside(false)
        giftDialog.show()
        giftDialog.setGiftTitleText(getString(R.string.points_sign))
        giftDialog.setGiftPointText(String.format(getString(R.string.points_count),signPoints))
        giftDialog.setGiftPointTips(String.format(getString(R.string.points_sign_count),signPoints))
        giftDialog.setGiftButtonText(getString(R.string.click_ok))
    }

    /**
     * 需要校验手机号
     */
    override fun showMainCheckNumberPage() {
//        val mainProductName = ShipweConfigs.SHIPWE_APPNAME
//        val mainProductToken = ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_TOKEN)
//        ActivityCheckNumber.start(this,mainProductName,mainProductToken)
    }

    override fun onShipwePublishEvent(event: AppEventData) {
        super.onShipwePublishEvent(event)
        ShipweLogger.e(">>>>>>>>>>main>>>>>>>>>>>sub event："+event.eventType)
        when(event.eventType){
            AppEventData.TYPE.SHIPWE_PROCESS_REFRESH -> {//刷新流程
                presenter?.loadAppProcessAction()
            }
            AppEventData.TYPE.SHIPWE_SHOW_HOME -> {//显示首页
                binding.viewPager.currentItem = 0
            }
            AppEventData.TYPE.SHIPWE_SHOW_REPAY -> {//待还款
                binding.viewPager.currentItem = 1
            }
            AppEventData.TYPE.SHIPWE_PRODUCT_REFRESH -> {//刷新产品
                presenter?.loadAppProductListAction()
            }
            AppEventData.TYPE.SHIPWE_POINTS_REFRESH -> {//刷新积分
                presenter?.getMainUserSignInfoAction()
            }
            else -> {

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        MainFragmentFactory.clear()
    }
}